package com.xmuexp109.exp5.Controller;

import com.xmuexp109.exp5.model.VoObject;
import com.xmuexp109.exp5.model.ordersRetVo;
import com.xmuexp109.exp5.model.ordersVo;
import com.xmuexp109.exp5.util.ResponseCode;
import com.xmuexp109.exp5.util.ResponseUtil;
import com.xmuexp109.exp5.util.ReturnObject;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import static com.xmuexp109.exp5.util.Common.*;

/**
 * 订单控制器
 */
@Api(value = "订单API", tags = "订单API")
@RestController /*Restful的Controller对象*/
@RequestMapping(value = "/orders", produces = "application/json;charset=UTF-8")
public class ordersController {

    @Autowired
    private com.xmuexp109.exp5.service.ordersService ordersService;

    @Autowired
    private HttpServletResponse httpServletResponse;

    @ApiOperation(value = "通过id获取订单",  produces="application/json;charset=UTF-8")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "Integer", name = "id", value ="订单对象id" ,required = true)
    })
    @ApiResponses({
    })
    @GetMapping("{id}")
    public Object getGoodsById(@PathVariable("id") Long id) {
        ReturnObject<VoObject> returnObject =  ordersService.findById(id);
        ResponseCode code = returnObject.getCode();
        switch (code){
            case RESOURCE_ID_NOTEXIST:
                httpServletResponse.setStatus(HttpStatus.NOT_FOUND.value());
                return ResponseUtil.fail(returnObject.getCode(), returnObject.getErrmsg());
            case OK:
                ordersRetVo ordersRetVo = (ordersRetVo) returnObject.getData().createVo();
                return ResponseUtil.ok(ordersRetVo);
            default:
                return ResponseUtil.fail(code);
        }
    }

    @ApiOperation(value = "新建订单",  produces="application/json")
    @ApiImplicitParams({
    })
    @ApiResponses({
    })
    @PostMapping("")
    public Object createOrder(@Validated @RequestBody ordersVo ordersVo, BindingResult bindingResult){

        Object returnObject = processFieldErrors(bindingResult, httpServletResponse);
        if (null != returnObject){
            return returnObject;
        }
        ReturnObject<VoObject> returnObject1 = ordersService.createOrders(ordersVo);
        httpServletResponse.setStatus(HttpStatus.CREATED.value());
        return getRetObject(returnObject1);
    }

}
